<template>
  <div class="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索栏与添加用户框 -->
    <div style="margin-top: 15px">
      <el-input
        placeholder="请输入内容"
        class="input-with-select"
        style="width: 300px"
        @keyup.native.enter='searchUserList'
        v-model="searchKey"
      >
        <el-button slot="append" icon="el-icon-search" @click='searchUserList'></el-button>
      </el-input>
      <el-button type="success" plain @click='adddialogFormVisible = true'>添加用户</el-button>
    </div>
    <!-- 用户表格 -->
    <el-table :data="userList" border style="width: 100%;margin-top:15px;">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" plain @change='changeUserState(scope.row)'></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" plain @click='showEditForm(scope.row)'></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="primary" icon="el-icon-delete" plain @click='showDelForm(scope.row.id)'></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="授权角色" placement="top">
            <el-button type="primary" icon="el-icon-share" plain @click='showGrantForm(scope.row)'></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      style="background: #eee; margin-top: 15px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 用户添加 -->
    <el-dialog title="添加用户" :visible.sync="adddialogFormVisible">
      <el-form :model="addUserForm" :rules="rules" ref="addUserForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addUserForm.password" type='password' autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 用户编辑 -->
    <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editsubmitForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 授权角色 -->
    <el-dialog title="授权角色" :visible.sync="grantdialogFormVisible">
      <el-form :model="grantForm" ref="grantForm">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="grantForm.username" autocomplete="off" disabled style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <template>
            <!-- 双向绑定得value可以获得:value的值，当值改变的时候（chang） -->
            <el-select v-model="rolevalue" placeholder="请选择" @change = changePower>
              <el-option
                v-for="item in powerList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantsubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllUsersList, addUser, editUser, delUser, changeUser, getUserPowerList, assignRoles } from '@/api/index.js'
export default {
  data () {
    return {
      userList: [],
      pageNum: 1,
      total: 1,
      pages: 10,
      searchKey: '',
      adddialogFormVisible: false,
      formLabelWidth: '80px',
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editdialogFormVisible: false,
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      grantdialogFormVisible: false,
      grantForm: {
        id: '',
        rid: '',
        username: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        mobile: [
          { required: true, message: '电话不能为空' }
        ]
      },
      powerList: [],
      rolevalue: ''
    }
  },
  mounted () {
    this.getPages()
  },
  methods: {
    // 获取页面信息的函数
    getPages () {
      getAllUsersList({query: this.searchKey, pagenum: this.pageNum, pagesize: this.pages}).then(res => {
        console.log(res.data)
        this.total = res.data.total
        this.userList = res.data.users
      })
    },
    // 搜索用户函数
    searchUserList () {
      this.getPages()
    },
    // 每页条数发生变化时候触发的函数
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pages = val
      this.getPages()
    },
    // 页数发生变化时候触发的函数
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pageNum = val
      this.getPages()
    },
    // 添加用户
    submitForm (addUserForm) {
      this.$refs[addUserForm].validate((valid) => {
        if (valid) {
          addUser(this.addUserForm).then(res => {
            // console.log(res)
            if (res.meta.status === 201) {
              this.$message.success('添加用户成功')
            }
            // 隐藏对话框
            this.adddialogFormVisible = false
            // 重置表单
            this.$refs[addUserForm].resetFields()
            // 刷新页面
            this.getPages()
          })
        } else {
          this.$message.error('添加用户失败')
          return false
        }
      })
    },
    // 打开编辑用户框
    showEditForm (val) {
      console.log(val)
      this.editdialogFormVisible = true
      this.editForm.id = val.id
      this.editForm.username = val.username
      this.editForm.email = val.email
      this.editForm.mobile = val.mobile
      console.log(this.editForm.id)
    },
    // 编辑用户
    editsubmitForm (editForm) {
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          editUser(this.editForm).then(res => {
            // console.log(res)
            if (res.meta.status === 200) {
              // 关闭编辑框
              this.editdialogFormVisible = false
              // 成功提醒
              this.$message.success(res.meta.msg)
              // 刷新页面
              this.getPages()
            }
          })
        } else {
          this.$message.error('编辑用户失败')
          return false
        }
      })
    },
    // 删除用户
    showDelForm (id) {
      this.$confirm(`此操作将永久删除id号为${id}文件, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(id).then(res => {
          // console.log(res)
          this.$message.success(res.meta.msg)
          // 刷新页面
          this.getPages()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 更改用户状态
    changeUserState (val) {
      changeUser(val).then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          // 关闭编辑框
          this.editdialogFormVisible = false
          // 成功提醒
          this.$message.success(res.meta.msg)
          // 刷新页面
          this.getPages()
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    // 打开授权角色用户框
    showGrantForm (val) {
      this.grantdialogFormVisible = true
      this.grantForm.id = val.id
      this.grantForm.username = val.username
      // 发送请求
      getUserPowerList().then(res => {
        this.powerList = res.data
      })
    },
    // 获取选项框变化的id
    changePower () {
      this.grantForm.rid = this.rolevalue
    },
    // 修改授权角色
    grantsubmitForm () {
      assignRoles(this.grantForm).then(res => {
        if (res.meta.status === 200) {
          // 关闭编辑框
          this.grantdialogFormVisible = false
          // 成功提醒
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
